<template>
  <div id="cesium-viewer">
    <slot />
  </div>
</template>

<script setup>
import * as Cesium from "cesium";
import { onMounted, ref, markRaw } from "vue";
import app from "../main";
import {
  initViewer,
  setScene,
  loadTilesets,
  handleDefaultModelEffect,
  flyToDefaultView,
} from "@/cesiumTools/sceneManager";
import { getLine } from "@/api/line";
import { useLineData } from "@/store";
const lineDataStore = useLineData();
//初始化cesium实例
Cesium.Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3ODAzN2EzOS1kZDMzLTQ5Y2UtYjYxMi1jMzQxNTdiMTUzN2IiLCJpZCI6NDU5NDIsImlhdCI6MTYxNTYyNDQyOX0.BucgmI6OJ-7ixj7rcQ_Qyg45DkvdHmaLrFwyMYitLcI";

onMounted(async () => {
  // 加载视图
  const viewer = initViewer("cesium-viewer");
  lineDataStore.setViewer(markRaw(viewer));
  setScene(viewer);
  flyToDefaultView(viewer);

  // 加载3dtiles
  const modelUrls = [
    {
      url: "http://localhost:8888/wuhan/tileset.json",
      options: {},
    },
  ];
  await loadTilesets(viewer, modelUrls, (tilesets) => {
    handleDefaultModelEffect(tilesets[0]);
    app.provide("$viewer_tile", { viewer, tilesets });
    lineDataStore.setTileset(markRaw(tilesets[0]));
  });

  // 获取线路数据
  const res = await getLine({});
  //markRaw函数用于把某个数据，标记为普通对象
  lineDataStore.setData(markRaw(res));

  for (let i = 0; i < res.length; i++) {
    const geometryInfo = res[i].paths;
    let positions = [];
    for (let j = 0; j < geometryInfo.length; j++) {
      positions.push(
        Cesium.Cartesian3.fromDegrees(
          geometryInfo[j].lng,
          geometryInfo[j].lat,
          0
        )
      );
    }
    const polyline = viewer.entities.add({
      name: "Polyline",
      polyline: {
        positions: positions,
        width: 5,
        material: new Cesium.PolylineOutlineMaterialProperty({
          color: Cesium.Color.fromRandom().withAlpha(0.5),
          outlineWidth: 2,
          outlineColor: Cesium.Color.BLACK,
        }),
      },
    });
  }
});
</script>
<style>
#cesium-viewer {
  width: 100%;
  height: 100%;
  pointer-events: all;
}
</style>
